package jmind.core.ip;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 身份证号码工具类
 * 
 */
public class Pin {

	static final int[] wi = { 7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2, 1 };

	static final char[] vi = { '1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2' };

	private int[] ai = new int[18];
	/*
110101 东城区
110102 西城区
110103 崇文区
110104 宣武
110105 朝阳区
110106 丰台区
110107 石景山
110108 海淀区
110109 门头
110111 房山
110221 昌平
110222 顺义
110223 通县
110224 大兴
110226 平谷
110227 怀柔
110228 密云
110229 延庆 
	 */
	static final String[][] bjd = {{"","东城区","西城区","崇文区","宣武区","朝阳区","丰台区","石景山区","海淀区","门头沟区"},
		{"","房山区","","","","","","","",""},
		{"","昌平区","顺义区","通州区","大兴区","","平谷区","怀柔区","密云县","延庆县"}}; 
	static final Pattern bjdp =Pattern.compile("^110[12]([012])([1-9])\\d{11}[0-9X]$"); 
	public Pin() {
	}

	// 验证15位18位
	public boolean verify(String idcard) {
		if (idcard.length() == 15) {
			idcard = uptoeighteen(idcard);
		}
		if (idcard.length() != 18) {
			return false;
		}
		char verifyd = idcard.charAt(17);
		if (verifyd == getVerify(idcard)) {
			return true;
		}
		return false;
	}

	// 得到最后地位校验码
	public char getVerify(String eightcardid) {
		int remaining = 0;

		if (eightcardid.length() == 18) {
			eightcardid = eightcardid.substring(0, 17);
		}

		if (eightcardid.length() == 17) {
			int sum = 0;
			for (int i = 0; i < 17; i++) {
				String k = eightcardid.substring(i, i + 1);
				ai[i] = Integer.parseInt(k);
				// System.out.println(ai[i]);
			}

			for (int i = 0; i < 17; i++) {
				sum = sum + wi[i] * (ai[i]);
				// System.out.println(sum+">>>"+wi[i]);
			}
			remaining = sum % 11;
			// System.out.println(remaining);//得到vi的第几位
		}
		return  (vi[remaining]);
	}

	// 15转18位
	public String uptoeighteen(String fifteencardid) {
		String eightcardid = fifteencardid.substring(0, 6);
		eightcardid = eightcardid + "19";
		eightcardid = eightcardid + fifteencardid.substring(6, 15);
		eightcardid = eightcardid + getVerify(eightcardid);
		return eightcardid;
	}

	public static void main(String[] args) {
		Pin pin = new Pin();
		for(String a : args){
			pin.printBjd(a);
		}
	}
	private void printBjd(String idcard){
		System.out.println(idcard+":"+getBjd(idcard));
	}
	/**
	 * 通过身份证得到北京市区县
	 * @param idcard 身份证号码，15位或者18位
	 * @return 北京市区县名称或者空字符串(北京市未知区)或者null(非北京市)
	 */
	public String getBjd(String idcard){
		if (idcard.length() == 15) {
			idcard = uptoeighteen(idcard);
		}
		if(!verify(idcard)){
			return null;
		}
		Matcher m = bjdp.matcher(idcard);
		if(m.matches()){
			int k1 = Integer.parseInt(m.group(1));
			int k2 = Integer.parseInt(m.group(2));
			return bjd[k1][k2];
		}else{
			return null;
		}
	}
}